package cn.dlc.com.service.impl;

import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.dlc.com.lock.DbLock;
import cn.dlc.com.lock.RedisLock;
import cn.dlc.com.mapper.Stock;
import cn.dlc.com.mapper.StockMapper;
import cn.dlc.com.service.StockService;
import tk.mybatis.mapper.entity.Example;

/**
 * 
 * Copyright: Copyright (c) 2020 
 * 
 * @ClassName: StockServiceImpl.java
 * @Description: 实现库存的修改，
 *
 * @version: v1.0.0
 * @author: 立川
 * @date: 2020年8月26日 上午6:53:37
 */
@Service
public class StockServiceImpl implements StockService{

	@Autowired
	private StockMapper stockMapper;
	
	@Autowired
	private DbLock dbLock;
	
	@Autowired
	private RedisLock redisLock;
	
	@Autowired
	private RLock rlock;
	
	@Override
	public boolean reduceStock(String id, Integer num) throws Exception{
		
		// 上锁
		dbLock.lock();
		
		Example example = new Example(Stock.class);
		example.createCriteria().andEqualTo("id", id);
		// 先查出来
		Stock stock = stockMapper.selectOneByExample(example);
		if(stock != null && stock.getStock() > 0) {
			// 减掉库存，
			Thread.sleep(3000);
			Integer result = stock.getStock() - num;
			stock.setStock(result);
			// 塞回去
			stockMapper.updateByPrimaryKey(stock);
			// 释放锁
			dbLock.unlock();
			return true;
		} else {
			// 释放锁
			dbLock.unlock();
			return false;
		}
	}

	@Override
	public boolean reduceStockRedis(String id, Integer num) throws Exception {
		// 上锁
//		redisLock.lock();
		// 这个lock可以设置过期时间和时间单位，
		rlock.lock();
		
		Example example = new Example(Stock.class);
		example.createCriteria().andEqualTo("id", id);
		// 先查出来
		Stock stock = stockMapper.selectOneByExample(example);
		if(stock != null && stock.getStock() > 0) {
			// 减掉库存，
			Thread.sleep(5000);
			Integer result = stock.getStock() - num;
			stock.setStock(result);
			// 塞回去
			stockMapper.updateByPrimaryKey(stock);
			// 释放锁
//			redisLock.unlock();
			rlock.unlock();
			return true;
		} else {
			// 释放锁
//			redisLock.unlock();
			rlock.unlock();
			return false;
		}
	}
	
	
}
